<template>
  <Container class="account-edit">
    <div class="container-header title title-center" slot="header">
      {{title}}
      <Button size="large" class="fl btn-back"  icon="ios-arrow-back" @click="jumpPrevPage">返回</Button>
    </div>
    <div class="bg-light">
      <div class="container-title">基础信息</div>
      <Form :model="form" :label-width="80" :rules="ruleValidate" ref="form">
        <Row>
          <Col span="8">
            <FormItem label="姓名" prop="realName">
              <Input :maxlength="20" type="text" v-model.trim="form.realName"/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="8">
            <FormItem prop="mobile" label="手机号">
              <Input type="text" v-model.trim="form.mobile" placeholder="请输入手机号"/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="8">
            <FormItem prop="email" label="E-mail">
              <Input type="text" v-model.trim="form.email" placeholder="请输入邮箱地址"/>
            </FormItem>
          </Col>
        </Row>
        <template v-if="id">
          <Row>
            <Col span="8">
              <FormItem prop="password" label="密码">
                <Input 
                  :type="pwdType"
                  v-model.trim="form.newPassword" 
                  icon="ios-eye"
                  :maxlength="16"
                  @on-click="changeEye('passwdFlag')"
                  placeholder="输入密码，6-16个字符"/>
              </FormItem>
            </Col>
          </Row>
        </template>
        <template v-else>
          <Row>
            <Col span="8">
              <FormItem label="密码" v-if="passwdFlag" class="require-account">
                <Input 
                  :type="pwdType" 
                  v-model.trim="form.password"
                  :maxlength="16"
                  icon="eye-disabled"
                  @on-change="changeType"
                  @on-click="changeEye('passwdFlag')"
                  placeholder="输入密码，6-16个字符"/>
              </FormItem>
              <FormItem prop="password" label="密码" v-else>
                <Input 
                  :type="pwdType"
                  v-model.trim="form.password" 
                  icon="ios-eye"
                  :maxlength="16"
                  @on-click="changeEye('passwdFlag')"
                  placeholder="输入密码，6-16个字符"/>
              </FormItem>
            </Col>
          </Row>
        </template>
        <Row>
          <Col span="8">
            <FormItem label="部门">
              <Input :maxlength="8" v-model.trim="form.department" placeholder="输入部门/分部名称"/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="8">
            <FormItem label="是否开启">
              <Checkbox v-model="form.isEnabled"></Checkbox>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="8">
            <FormItem label="是否锁定">
              <Checkbox v-model="form.isLocked"></Checkbox>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </div>
    <div class="bg-light">
      <div class="container-title">角色选择</div>
      <Form :model="form" :label-width="80" class="pl pb">
        <Row>
          <Col>
            <CheckboxGroup v-model="form.roleIds">
              <Checkbox :label="item.id" v-for="item in roleArr" :key="item.id">{{item.label}}</Checkbox>
            </CheckboxGroup>
          </Col>
        </Row>
      </Form>
    </div>
    <div class="container-footer bg-white" slot="footer">
      <Button type="primary" :disabled="btnDisabled" class="mr" size="large" @click="handleSubmit">确定</Button>
    </div>
  </Container>
</template>
<script>
import { clearEmpty, telReg } from '@/util'
export default {
  data() {
    const validateMobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (value.length != 11) {
        callback(new Error('请输入正确的手机号'))
      } else if (!telReg.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入姓名'))
      } else {
        callback()
      }
    }
    return {
      id: this.$route.query.id || '',
      title: '',
      btnDisabled: false,
      passwdFlag: true,
      pwdType: 'text',
      ruleValidate: {
        realName: [
          { required: true, validator: validateUsername, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱地址不允许为空', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      },
      options: {
        tableHeight: 300
      },
      form: {
        realName: '',
        email: '',
        password: '',
        mobile: '',
        isEnabled: false,
        roleIds: [],
        department: '',
        isLocked: false,
        oldPassword: '',
        newPassword: ''
      },
      roleArr: [],
      isMaster: false
    }
  },
  mounted() {
    this.getAllRoles()
    if (this.$route.query.id) {
      this.title = '编辑账号'
      this.id = this.$route.query.id
      this.getDetail()
    } else {
      this.title = '新增账号'
    }
  },
  methods: {
    getDetail() {
      let param = {
        id: this.id
      }
      this.$ajaxGet('/supplier/supplier_user/find', param).then(data => {
        this.form.realName = data.realName
        this.form.email = data.email
        this.form.isEnabled = data.isEnabled
        this.form.mobile = data.mobile
        this.form.isLocked = data.isLocked
        this.form.department = data.department
        this.form.password = data.password
        this.form.roleIds = data.roleIds
        this.isMaster = data.isMaster
        // data.roleDTOs.forEach(item => {
        //   this.form.roleIds.push(item.id)
        // })
      })
    },
    getAllRoles() {
      this.$ajaxGet('/supplier/role/list').then(data => {
        this.roleArr = (data || []).map(item => {
          return {
            id: item.id,
            label: item.name
          }
        })
        if(this.id && this.isMaster) {
          this.roleArr = [{'id': '0', 'label': '我是超级管理员'}].concat(this.roleArr)
        }
      })
    },
    jumpPrevPage() {
      this.$router.back()
    },
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.roleIds.length === 0) {
            this.$Notice.error({
              title: '请选择角色'
            })
            return
          }
          if (!this.id) {
            if (!this.form.password) {
              this.$Notice.error({
                title: '请输入密码'
              })
              return
            }
          }
          let reg = /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{6,16}$/
          if (this.form.password.length < 6 && this.form.password.length >= 1) {
            this.$Notice.error({
              title: '密码长度至少为6位'
            })
            return
          }
          if (this.form.password.length > 1 && reg.test(this.form.password)) {
            this.$Notice.error({
              title: '请输入正确的密码格式'
            })
            return
          }
          this.btnDisabled = true
          let param = {}
          param.realName = this.form.realName
          param.email = this.form.email
          // param.password = this.form.password
          if (this.id) {
            param.newPassword = this.form.newPassword
          } else {
            param.password = this.form.password
          }
          param.mobile = this.form.mobile
          param.isEnabled = this.form.isEnabled
          param.roleIds = this.form.roleIds
          param.department = this.form.department
          param.isLocked = this.form.isLocked
          param = clearEmpty(param)
          if (this.id) param.id = this.id
          let text = this.id ? '编辑' : '新增'
          let url = this.id ? '/supplier/supplier_user/update' : '/supplier/supplier_user/add'
          this.$jsonPost(url, param).then(data => {
            this.$Notice.success({
              title:`${text}成功`
            })
            this.$router.push('/setting/account/list')
          }).catch(() =>{
            this.btnDisabled = false
          })
        }
      })
    },
    changeEye(type) {
      this[type] = !this[type]
      this.pwdType = this.pwdType === 'password' ? 'text' : 'password'
    },
    changeType() {
      this.pwdType = 'password'
    }
  }
}
</script>